<?php
namespace control;


class visitRecordsClass extends adIndexClass
{
    private const title = '客户走访记录';
    private const page = 'visitRecords';
    private const table = 'visit_records';
    private const tableAddr = 'sales_contract_address'; # 地址表

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo' => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'khid' => [
                        'name'  => "客户",
                        'width' => 150,
                    ],
                    'theme'          => [
                        'name'  => '来访目的',
                        'width' => 200,
                    ],
                    'createTime'  => [
                        'name'  => "走访日期",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'achievement'         => [
                        'name'  => '问题及需求',
                        'width' => 150,
                    ],
//                    'imageArr'         => [
//                        'name'  => '走访图片',
//                        'width' => 150,
//                    ],
                    'khSituation'         => [
                        'name'  => '客户基本情况',
                        'width' => 150,
                    ],
                    'content'         => [
                        'name'  => '走访内容',
                        'width' => 150,
                    ],
                    'stid'          => [
                        'name'  => '业务经理',
                        'width' => 150,
                    ],
                    'time'          => [
                        'name'  => '单据日期',
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    '单据编号' => text(array("name" => "orderNo")),
                    '客户名称'   => clientClass::kehuSelect(array('name' => 'khid')),
                    '来访目的' => text(array("name" => "theme")),
                ],
                [
                    '走访日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    '问题及需求' => text(array("name" => "achievement")),
                    '业务经理' => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    '单据日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
            ]
        ];
        //生成查询表单
        $html = $this->tableShow($array);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        $url    = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "theme" => $this->post('theme'),//来访目的
        );
        //全等查询数组
        $equal = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "khid" => $this->post('khid'),//客户
            "stid" => $this->post('stid'),//产品经理
        );
        //公私客
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'),'date','createTime');
        }
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit"    => ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"],
                "detail"  => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {

                    case "khid":
                        $kehu  = query('kehu', " khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case "stid":
                        $staff  = query('staff', " stid = '$array[stid]'");
                        $row[] = $staff['name'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     *上传走访图片
     */
    function uploadIco(): bool|string
    {
        $type = $this->post('type');
        $result = $this->saveFile($_FILES['imgFile'], 'supplier', explode(',', para('fileFormat')));
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        }elseif (empty($type)) {
            $json['warn'] = '未找到类型';
        }elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } elseif (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $field = array(
                'src'=>$result['src'],
                'name'=>$result['fileName'],
                'size'=>$result['size'],
                'format'=>$result['suffix'],
            );
            $file = query('file',"targetId = '$id' and target = '$type'");
            if (empty($file['id'])){
                $field = array_merge($field,[
                    'id'=>self::getId(),
                    'stid'=>self::$stid,
                    'target'=>$type,
                    'targetId'=>$id,
                ]);
                $json['warn'] =static::insert(array(
                    'table'=>'file',
                    'field'=>$field
                ));
                $fileId = $field['id'];
            }else{
                $json['warn'] =static::update(array(
                    'table'=>'file',
                    'field'=>$field,
                    'where'=>"id = '$file[id]'"
                ));
                $fileId = $file['id'];
            }
            //添加日志
            if (in_array($json['warn'] ,['新增成功','更新成功'])) {
                fileDelete($file['src']);//删除之前的图片
                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
                $json['data']['fileHtml'] = hidden(array('name'=>"imgId[]",'value'=>$fileId));
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id   = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name"  => "保存",
            "type"  => "点击事件",
            "title" => "保存为草稿",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        //表单
        $data['button'] = $this->tableShowButton($button);
        $licenseUrl = query('file',"targetId = '$info[id]' and target ='走访图片'");
        $photo = array(
            array("title" => "走访图片", 'type' => '走访图片', 'fileId'=>$licenseUrl['id'] ?? '', "url" => $licenseUrl['src'] ?? '','id'=>$info['id']),
        );
        $talentObj = new talentPoolClass();
        $body           = $this->edit4([
            '基本信息' => [
                [
                    must . "客户：" => clientClass::kehuSelect(array('name' => 'khid','value'=>$info['khid'])),
                    must . "走访目的：" => text(["name" => "theme", 'class' => 'text', "value" => $info['theme']]),
                    must . "走访日期：" => text(["name" => "createTime", 'laydate' => [], 'class' => 'text', "value" => $info['createTime']]),
                ],
                [
                    "问题及需求：" =>textarea(["name" => "achievement", 'class' => 'textarea', "value" => $info['achievement']]),
                    "客户基本情况：" =>textarea(["name" => "khSituation", 'class' => 'textarea', "value" => $info['khSituation']]),
                    "走访内容：" =>textarea(["name" => "content", 'class' => 'textarea', "value" => $info['content']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ],
            '其他信息' => [
                [
//                    self::singlePhoto($photo)
                    $talentObj->photo($photo)

                ]
            ],
        ]);
        $data['html'] = $this->pageEdit([
                "html"   => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]). "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco')\"></div>",
            ]);
        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $fileId = $this->post('imgId');
        $field = [
            'khid' => $this->post('khid'),
            'theme' => $this->post('theme'),
            'createTime' => $this->post('createTime'),
            'achievement' => $this->post('achievement'),
            'khSituation' => $this->post('khSituation'),
            'content' => $this->post('content'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'khid' => '客户',
            'theme' => '走访目的',
            'createTime' => '走访日期',
//            'achievement' => '问题及需求',
        ];
        $rules = [
            'khid' => 'required',
            'theme' => 'required',
            'createTime' => 'required',
//            'achievement' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }  else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'ZFJL',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //更新文件
                if (is_array($fileId) && !static::isNull($fileId)) {
                    update(['table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileId) . "')"]);
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data   = [
                "id" => $info['id'],
            ];
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name"  => "编辑",
                    "type"  => "顶部页卡",
                    "title" => "编辑信息",
                    "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                ];
            }
            if ($this->power(self::page, "del")) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //操作记录
            $kehu           = query('kehu', "khid = '$info[khid]'");
            $licenseUrl = query('file',"targetId = '$info[id]' and target ='走访图片'");
            $photo = array(
                array("title" => "走访图片", 'type' => '走访图片', 'fileId'=>$licenseUrl['id'] ?? '', "url" => $licenseUrl['src'] ?? '','id'=>$info['id']),
            );
            $talentObj = new talentPoolClass();
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow([
                '基本信息' => [
                    [
                        "客户：" => $kehu['companyName'],
                        "走访目的：" => $info['theme'],
                        "走访日期：" => self::null($info['createTime']),
                    ],
                    [
                        "问题及需求：" =>pre($info['achievement']),
                        "客户基本情况：" =>pre($info['khSituation']),
                        "走访内容：" =>pre($info['content']),
                    ],
                    [
                        "备注：" =>pre($info['text']),
                    ],
                ],
                '其他信息' => [
                    [
                        self::singlePhoto($photo)
                    ]
                ],
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * @param $data
     * @return string
     */
    public static function singlePhoto($data): string
    {
        $li = "";
        foreach ($data as $array) {
            //编辑表单
            $click = '';
            if (!empty($array['id'])) {
                $click = "<img  src='" . root . "img/images/clickEdit.png' onClick=\"clickUpload('{$array['type']}')\" class='clickIco'>";
            }
            //点击显示大图功能
            if (empty($array['url'])) {
                $img = "<img class='smallImg imgHover' data-type='{$array['type']}' src='" . root . "img/images/emptyImg.jpg'>";
            } else {
                if (strstr($array['url'], "http") !== false) {
                    $r = "";
                } else {
                    $r = root;
                }
                $img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img data-type='{$array['type']}' class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
            }
            //打印本图像框
            $li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
			</li>
			";
        }
        $data['cla'] = $data['cla']??self::page;
        return <<<efo
		
<form name="{$data['cla']}ImgSingleForm"><div class='imgSingle'>
			<ul>{$li}</ul>
			<div class='clear'></div>
		</div><div class='hidden'><input name="type" type="hidden" ><input name='imgFile' accept="image/*" id='imgFile' type='file' onchange="uploadImgFile('{$data['cla']}ImgSingleForm',root+'control/adIndex.html?cla={$data['cla']}&fun=uploadIco')"></div></form>
		<script>
		//点击上传图片
        function clickUpload(type){
            $('[name=type]').val(type);
            $('#imgFile').click();
        }
        //上传图片
        function uploadImgFile(formName,url){
            let form = $("form[name='"+formName+"']")[0];
            let id= $("[name='id']").val();
            let type = $("[name='type']").val();
            let formData = new FormData(form);
            formData.append('id',id);
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='imgFile']").val('');
                    if (result.warn === 2) {
                        $("[data-type='"+type+"']").attr('src',result.data.src);
                        $("[data-type='"+type+"']").nextAll().remove();
                        $("[data-type='"+type+"']").after(result.data.fileHtml)
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    console.log(e)
                    warn("上传失败");
                }
            });
        }
        </script>
efo;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $word = true;
        $form = $power = '';
        switch ($act) {

            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '执行此操作将删除选中的走访记录，删除后将无法找回，您确定要这么做吗？';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'word' => $word,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                delete(array("table" => "file", "where" => " targetId = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}